<template>
  <div class="article-page">
    <div class="banner">
      <div class="container">
        <h1>{{article.title}}</h1>

        <article-meta :article="article" />
      </div>
    </div>

    <div class="container page">
      <div class="row article-content">
        <div class="col-md-12" v-html="articleBody"></div>
      </div>

      <hr />

      <div class="article-actions">
        <article-meta :article="article" />
      </div>

      <article-comments
        :comments="comments"
        :article="article"
        @add-comment="addComment"
        @delete-comment="deleteComment"
      />
    </div>
  </div>
</template>

<script>
import {
  getArticle,
  getArticleComments,
  addArticleComment,
  deleteArticleComment,
} from '@/api/article.js'
import MarkdownIt from 'markdown-it'
import { mapState } from 'vuex'
import ArticleMeta from './components/meta.vue'
import ArticleComments from './components/comments.vue'
import UserImage from '@/pages/components/userImage.vue'
export default {
  name: 'Article',
  components: { ArticleMeta, UserImage, ArticleComments },
  data() {
    return {
      commentBody: '',
    }
  },
  async asyncData({ params }) {
    const { slug } = params
    const [articleRes, commentsRes] = await Promise.all([
      getArticle(slug),
      getArticleComments(slug),
    ])
    return {
      article: articleRes.data.article,
      comments: commentsRes.data.comments,
    }
  },
  computed: {
    ...mapState(['user']),
    articleBody() {
      if (this.article.body) {
        let md = new MarkdownIt()
        return md.render(this.article.body)
      } else {
        return 'there is no Body here...'
      }
    },
  },
  methods: {
    async addComment(body) {
      const { slug } = this.$route.params
      await addArticleComment(slug, this.commentBody)

      const { data } = await getArticleComments(slug)
      this.comments = data
    },
    async deleteComment(id) {
      const { slug } = this.$route.params
      await deleteArticleComment(slug, id)

      this.comments = this.comments.filter((m) => m.id !== id)
    },
  },
}
</script>